package com.haifeng.asms.api.handler;


import cn.hutool.core.exceptions.ExceptionUtil;
import com.haifeng.asms.commons.common.Rest;
import com.haifeng.asms.commons.exception.BusinessException;
import com.haifeng.asms.commons.exception.ValidException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 *  全局异常捕获
 * </p>
 * @Author: Haifeng
 * @Date: 2020-06-20
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 处理参数校验异常
     * @param exception
     * @return
     */
    @ExceptionHandler(ValidException.class)
    public Rest validException(ValidException exception){
        Rest restfulMessage = Rest.error(exception.getCode(),exception.getMessage());
        log.error("【项目发生参数校验异常】：{}", restfulMessage);
        return restfulMessage;
    }

    /**
     * 处理业务异常
     * @param exception
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Rest businessException(BusinessException exception){
        Rest restfulMessage = Rest.error(exception.getCode(),exception.getMessage());
        log.error("【项目发生业务异常】：{}", restfulMessage);
        return restfulMessage;
    }

    /**
     * 处理系统异常
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Rest globalException(Exception exception){
        Rest restfulMessage = Rest.error(ExceptionUtil.getMessage(exception));
        log.error("【项目发生异常】：{}", restfulMessage);
        exception.printStackTrace();
        return restfulMessage;
    }
}
